#include "MsgSetFilter.h"
#include "MsgError.h"
#include "MsgOK.h"
#include "BasicTypes.h"
#include "Model.h"
#include "Filter.h"

using namespace std;

class RegExErrorData : public IErrorData
{
private:
	int m_errorCode;
	int m_errorPos;
	string m_errorMsg;
public:
	RegExErrorData(InvalidFilterInfo info)
	{
		m_errorCode = info.errorCode;
		m_errorPos = info.errorPosition;
		m_errorMsg = info.errorMsg;
	};

	string Serialize()
	{
		string result;
		result.append((const char *)&m_errorCode, 4);
		result.append((const char *)&m_errorPos, 4);
		result.append(m_errorMsg);
		return result;
	}
};

MsgSetFilter::MsgSetFilter(const string & data)
{
	unsigned char filterType = data[0];
	type = (FilterType)filterType;
	filter = data.substr(1, data.length() - 1);
}

POutputMessage MsgSetFilter::Process(Model * model)
{
	if ( (type >= FT_Minimum) && (type <= FT_Maximum) )
	{
		try
		{
			auto_ptr<IFilter> f = IFilter::Create(type, filter);
			model->SetFilter(f);
			return POutputMessage(new MsgOK());
		}
		catch (InvalidFilterInfo info)
		{
			model->SetFilter(auto_ptr<IFilter>());
			return POutputMessage(new MsgError(ERR_INVALID_FILTER, *model, new RegExErrorData(info)));
		}
		catch (...)
		{
			model->SetFilter(auto_ptr<IFilter>());
			return POutputMessage(new MsgError(ERR_INTERNAL_ERROR, *model, NULL));
		}
	} else {
		model->SetFilter(auto_ptr<IFilter>());
		return POutputMessage(new MsgError(ERR_UNKNOWN_FILTER_TYPE, *model, NULL));
	}
	return POutputMessage();
}